﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Money
{
    public class Account
    {
        [NonSerialized]
        private static Transactions _transactions;

        // TODO add an account number for storing against transactions rather than a name. this would need a way of updating current imported records.
        public string Name { get; set; }
        public string Parser { get; set; }
        public string FilenameTemplate { get; set; }
        public string StatementPath { get; set; }
        public decimal OpeningBalance { get; set; }

        public decimal TransactionBalance
        {
            get
            {
                if (_transactions != null && _transactions.Count > 0)
                {
                    var summary = from transaction in _transactions where transaction.Account.Equals(Name) group transaction by transaction.Account into transactionGroup select new { Name = transactionGroup.Key, Balance = transactionGroup.Sum(t => t.Amount) };

                    if (summary != null && summary.Count() > 0)
                    {
                        return summary.ToList()[0].Balance;
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
        }

        public static void SetTransactions(Transactions transactions)
        {
            _transactions = transactions;
        }

        public void Update(Account account)
        {
            Name = account.Name;
            Parser = account.Parser;
            FilenameTemplate = account.FilenameTemplate;
            StatementPath = account.StatementPath;
            OpeningBalance = account.OpeningBalance;
        }

        public Account Copy()
        {
            Account account = (Account)this.MemberwiseClone();

            return account;
        }
    }
}
